<?php

namespace App\Models\Payment;

use App\Models\Common\Channel\Channel;
use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

/**
 * App\Models\Payment\ChannelPayment
 *
 * @property int         $id
 * @property string      $appid appid
 * @property string      $mchid 商户id
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @method static Builder|ChannelPayment newModelQuery()
 * @method static Builder|ChannelPayment newQuery()
 * @method static Builder|ChannelPayment query()
 * @method static Builder|ChannelPayment whereAppid($value)
 * @method static Builder|ChannelPayment whereCreatedAt($value)
 * @method static Builder|ChannelPayment whereId($value)
 * @method static Builder|ChannelPayment whereMchid($value)
 * @method static Builder|ChannelPayment whereUpdatedAt($value)
 * @mixin Eloquent
 */
class ChannelPayment extends Model
{
    use HasFactory;

    protected $table = 'channel_payment';
    protected $fillable
                     = [
            'appid', 'mchid',
        ];

    public function bind(Channel $channel, Payment $payment)
    {
        $data = ['appid' => $channel->getAppId(), 'mchid' => $payment->getMchId()];
        return $this->firstOrCreate($data);
    }

    public function getAppId(): string
    {
        return $this->getAttribute('appid');
    }

    public function getMchId(): string
    {
        return $this->getAttribute('mchid');
    }

    public function findOneByAppId(string $appid): ?self
    {
        $cache_key = "ChannelPayment:{$appid}";
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }
        $cp = $this->where('appid', $appid)->first();
        if ($cp) {
            Cache::put($cache_key, $cp, config('trip.ttl.day'));
        }
        return $cp;
    }
}
